<template>
  <div class="login">
    <div class="login-left-box">
      <el-carousel height="100vh">
        <el-carousel-item v-for="item in 1" :key="item">
          <div class="banner-item" :style="{'background-image':'url('+require('@/assets/images/banner-'+item+'.png')+')'}"></div>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="form-box">
      <div class="header-box">
        <img src="../assets/images/icon-logo.png" alt="">
        <div class="title">霖华AI双录</div>
        <div class="sub-title">欢迎使用霖华AI双录商户端系统</div>
      </div>
      <div class="login-type">
        <div :class="{active:loginForm.type==1}" @click="loginTypeChange(1)">账号登录</div>
        <div :class="{active:loginForm.type==3}" @click="loginTypeChange(3)">手机号登录</div>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" v-if="loginForm.type==1">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 66%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 15px;">记住密码</el-checkbox>
        <el-form-item class="button-mar-b">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            class="login-btn"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" v-else>
        <el-form-item prop="phonenumber">
          <el-input v-model="loginForm.phonenumber" type="number" maxLength="11" auto-complete="off" placeholder="手机号码">
            <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            type="number"
            auto-complete="off"
            placeholder="短信验证码"
            style="width: 75%"
            @keyup.enter.native="handleLoginPhone"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="get-code" :class="{disabled:codeText!='发送验证码'}" @click="getPhoneCode">{{codeText}}</div>
        </el-form-item>
        <el-form-item style="margin-top: 32px;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            class="login-btn"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright ©2024 霖华AI双录</span>
    </div>
    <el-dialog title="修改密码" :visible.sync="open" append-to-body width="500px">
      <el-form :model="updateForm" ref="updateForm" :rules="updateRules" label-width="68px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input placeholder="请输入用户名" v-model="updateForm.username"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="旧密码" prop="originalPassword">
              <el-input placeholder="请输入旧密码" v-model="updateForm.originalPassword" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="新密码" prop="newPassword">
              <el-input placeholder="请输入新密码" v-model="updateForm.newPassword" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCodeImg ,sendSmscode, forceUpdatePwd} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getRouters } from '@/api/common'

export default {
  name: "Login",
  data() {
    return {
      open:false,
      ddCodeShow: true,
      codeUrl: "",
      cookiePassword: "",
      codeText:'发送验证码',
      loginForm: {
        type: 1,
        username: "rec@admin",
        password: "zulin@admin123",
        phonenumber: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        phonenumber: [
          { required: true, trigger: "blur", message: "手机号不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      loading: false,
      redirect: undefined,
      updateForm: {
        username:'',
        originalPassword:'',
        newPassword:''
      },
      updateRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        originalPassword: [
          { required: true, trigger: "blur", message: "旧密码不能为空" }
        ],
        newPassword: [{ required: true, trigger: "blur",message: "新密码不能为空" }]
      },
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  mounted(){
    window.addEventListener('message', this.messageChange);
  },
  beforeDestroy(){
    window.removeEventListener('message', this.messageChange)
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    loginTypeChange(index){
      this.loginForm.type = index
    },
    submitForm() {
      this.$refs["updateForm"].validate(valid => {
        if (valid) {
          forceUpdatePwd(this.updateForm).then( res => {
            this.$modal.msgSuccess("密码修改成功，请重新登录");
            this.open = false
            this.loginForm.password = ''
            this.loading = false;
            this.getCode();
          })
        }
      })
    },
    messageChange(event){
      // 这里的event.data 就是登录成功的信息
      if(event.data && event.data.code){
        this.$store.dispatch("Login", {accountCode:event.data.code,type:2}).then(() => {
          this.$router.push({ path: this.redirect || "/" });
        }).catch(err=>{
          this.ddCodeShow = false
          setTimeout(()=>{
            this.ddCodeShow = true
          })
        })
      };
    },
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        type: 1,
        phonenumber: "",
        code: "",
      };
    },
    getPhoneCode(){
      if(this.codeText == '发送验证码'){
        if(!this.loginForm.phonenumber){
          return this.$modal.msgError('请先输入手机号码')
        }
        sendSmscode({phonenumber: this.loginForm.phonenumber}).then(res => {
          let second = 59
          this.codeText = '已发送('+second+'s)'
          let interval = setInterval(()=>{
            --second
            this.codeText = '已发送('+second+'s)'
            if(second==0){
              this.codeText = '发送验证码'
              clearInterval(interval)
            }
          },1000)
        });
			}
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if(this.loginForm.type == 1){
            if (this.loginForm.rememberMe) {
              Cookies.set("username", this.loginForm.username, { expires: 30 });
              Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove('rememberMe');
            }
          }
          this.$store.dispatch("Login", this.loginForm).then((res) => {
           
            this.$router.push({ path: "/" }).catch(()=>{});
          }).catch((error) => {
            this.loading = false;
            this.getCode();
            // if(error == '105') {
            
            // }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  height: 100%;
  background: #fff;
  overflow: hidden;
  display: flex;
  .login-left-box{
    flex: 1;
    .banner-item{
      background-size: cover;
      background-position: center;
      width: 100%;
      height: 100vh;
    }
  }
}
.header-box{
  text-align: center;
  margin-bottom: 25px;
  .title {
    letter-spacing: 3px;
    font-weight: bold;
    font-size: 22px;
    margin: 10px 0 10px;
  }
  .sub-title{
    color: #aaa;
    font-size: 16px;
  }
  img{
    width: 48px;
    height: 48px;
  }
}
.form-box{
  align-items: center;  
  border-radius: 8px;
  padding: 80px 35px 0;
  width: 439px;
  height: 500px;
  margin-top: 80px;
}
.login-type{
  display: flex;
  margin-bottom: 20px;
  >div{
    flex: 1;
    cursor: pointer;
    font-size: 20px;
    color: #aaa;
    text-align: center;
    &.active{
      font-weight: bold;
      color: #1890ff;
    }
    &:last-child{
      border-left: 1px solid #eee;
    }
  }
}
.login-form {
  .el-input {
    height: 42px;
    ::v-deep .el-input__inner {
      height: 42px !important;
      font-size: 16px;
      padding-left: 32px;
    }
  }
  .input-icon {
    height: 42px;
    width: 16px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 30%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.get-code{
  float: right;
  margin-left: 10px;
  color: #1890ff;
  cursor: pointer;
  line-height: 42px;
  &.disabled{
    cursor: no-drop;
    color: #999;
  }
}
.login-btn {
  padding: 13px 20px;
  font-size: 16px;
  border-radius: 50px;
  width: 100%;
}
.login-code-img {
  height: 40px;
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #333;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  z-index: 2;
}
</style>